package a66weding.com.jiehuntong.pager;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.ToolsDayPlanActivity;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.DayplanTask;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.WedPlanTypeBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.StrUtil;
import a66weding.com.jiehuntong.fragment.BaseFragment;
import a66weding.com.jiehuntong.fragment.BaseToolsDayPlanFragment;
import a66weding.com.jiehuntong.fragment.IFragmentCallBack;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.view.ConfirmDialog;
import a66weding.com.jiehuntong.view.SwipteLayout;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/7/15
 * @description :
 */
public class ToolsPager_DayPlan_Home extends BaseFragment implements View.OnClickListener, OnNetResultListener {
    public ToolsDayPlanActivity mDayplayActivity;
    private LinearLayout mBackView;
    private LinearLayout mNetWorkFail;
    private ExpandableListView mContentList;
    private List<BaseToolsDayPlanFragment> mFragmentList;
    private ImageView mHeadAddtype;
    private ImageView mSwipeView;
    private ViewGroup mdataContentLay;
    private Button mRestoreModel;
    private LinearLayout mNoDataLay;
    private ViewGroup mProgressbar;
    private SwipteLayout mSwipeLay;
    private boolean networkAvailable;
    private boolean isDetailShow;
    private boolean isaddType;
    private boolean isRecoverType;
    private View modeldeail;
    private View mContentview;
    private View mContentItem;
    private String mDayPlantype;
    private MyExpandListAdapter mExpandAdapter;
    private PopupWindow mCommitpop;
    private TextView mAddtypeTv;
    private List<WedPlanTypeBean.DataBean> mTypeList = new ArrayList<WedPlanTypeBean.DataBean>();
    private EditText mTypeTitle;
    private PopupWindow popupWindow1;
    private PopupWindow msgPopupWindow;
    private int mCurrentGroupPosition;
    private int mCurrentChildPosition;
    private boolean isDeleteTAsk;//是否删除任务
    private boolean isDeleteType;//是否删除类型
    private boolean isEditType;
    private View mAddTypeView;
    private static int childNetRequest = 0;
    private static final int CHILDNETREQUESTSUCESS = 1;
    private static final int CHILDNETREQUESTFAIL = 2;
    private static final int NETWORKTIME = 3;
    private int groupPosition;
    private int childPosition2;
    private int groupPosition2;
    protected static final int HAVEDATA = 1;
    protected static final int NODATA = 0;
    protected static final int DATAERROR = 2;
    protected static final int NONET = 3;
    private static IFragmentCallBack callBack;
    private static int popCount = 0;
    public static ToolsPager_DayPlan_Home newInstance(IFragmentCallBack callBack2) {
        ToolsPager_DayPlan_Home frag = new ToolsPager_DayPlan_Home();
        callBack = callBack2;
        return frag;
    }
    @Override
    public View initView() {
        this.mDayplayActivity = (ToolsDayPlanActivity) getActivity();
        mContentview = View.inflate(mDayplayActivity, R.layout.tools_dayplan_content, null);
        mContentList = (ExpandableListView) mContentview.findViewById(R.id.lv_tools_dayplan_content);
        mAddtypeTv = (TextView) mContentview.findViewById(R.id.tv_addtype);
        mNetWorkFail = (LinearLayout) mContentview.findViewById(R.id.llay_netfailer);
        mBackView = (LinearLayout) mContentview.findViewById(R.id.llay_toolsheader_back);
        mHeadAddtype = (ImageView) mContentview.findViewById(R.id.tv_tools_dayplan_addtype1);
        mdataContentLay = (ViewGroup) mContentview.findViewById(R.id.llay_toolsdayplan_datacontent);
        mRestoreModel = (Button) mContentview.findViewById(R.id.btn_tools_dayplan_restore);
        mNoDataLay = (LinearLayout) mContentview.findViewById(R.id.llay_tools_dayplan_nodata);
        mProgressbar = (ViewGroup) mContentview.findViewById(R.id.progressBar);
        if (!networkAvailable) {
            mdataContentLay.setVisibility(View.GONE);
            mNoDataLay.setVisibility(View.GONE);
            mProgressbar.setVisibility(View.GONE);
            mNetWorkFail.setVisibility(View.VISIBLE);
            mNetWorkFail.setOnClickListener(this);
        }
        mdataContentLay.setVisibility(View.GONE);
        mNoDataLay.setVisibility(View.GONE);
        mBackView.setOnClickListener(this);
        mHeadAddtype.setOnClickListener(this);
        mAddtypeTv.setOnClickListener(this);
        mRestoreModel.setOnClickListener(this);
        if (mTypeList != null && mTypeList.size() > 0) {
            mExpandAdapter = new MyExpandListAdapter();
            mContentList.setAdapter(mExpandAdapter);
            mContentList.setGroupIndicator(null);
            mContentList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                @Override
                public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                    mContentList.expandGroup(groupPosition, false);
                    setListViewHeight(parent, groupPosition);
                    return false;
                }
            });

        }
        mAddTypeView = View.inflate(mDayplayActivity, R.layout.item_tools_dayplan_addtype0, null);
        return mContentview;
    }

    @Override
    public void initData() {
        super.initData();
        mHandler.sendEmptyMessageDelayed(NETWORKTIME, 50000);
        getDataFromServer();

    }

    public class MyExpandListAdapter extends BaseExpandableListAdapter {
        @Override
        public int getGroupCount() {
            return mTypeList.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            List<DayplanTask.DataBean> taskData = mTypeList.get(groupPosition).getTaskData();
            if (taskData == null || taskData.size() < 1) {
                return 1;
            }
            return taskData.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return mTypeList.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            List<DayplanTask.DataBean> taskData = mTypeList.get(groupPosition).getTaskData();
            if (taskData != null || taskData.size() > 0) {
                return taskData.get(childPosition);
            }
            return null;
        }

        /**
         * 获取指定组的ID，这个组ID必须是唯一的
         *
         * @param groupPosition
         * @return
         * @see android.widget.ExpandableListAdapter#getGroupId(int)
         */
        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        /**
         * 获取指定组中的指定子元素ID
         *
         * @param groupPosition
         * @param childPosition
         * @return
         * @see android.widget.ExpandableListAdapter#getChildId(int, int)
         */
        @Override
        public long getChildId(int groupPosition, int childPosition) {
            List<DayplanTask.DataBean> taskData = mTypeList.get(groupPosition).getTaskData();

            return childPosition;
        }

        /**
         * 组和子元素是否持有稳定的ID,也就是底层数据的改变不会影响到它们。
         *
         * @return
         * @see android.widget.ExpandableListAdapter#hasStableIds()
         */
        @Override
        public boolean hasStableIds() {
            return true;
        }

        /**
         * 获取显示指定组的视图对象
         *
         * @param groupPosition 组位置
         * @param isExpanded    该组是展开状态还是伸缩状态
         * @param convertView   重用已有的视图对象
         * @param parent        返回的视图对象始终依附于的视图组
         * @return
         * @see android.widget.ExpandableListAdapter#getGroupView(int, boolean, android.view.View,
         * android.view.ViewGroup)
         */
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            WedPlanTypeBean.DataBean typeBean = mTypeList.get(groupPosition);
            GroupHolder mHolder = null;
            if (convertView == null) {
                mHolder = new GroupHolder();
                convertView = View.inflate(mDayplayActivity, R.layout.item_tools_dayplan_contentitem, null);
                mHolder.mSwipeLay = (SwipteLayout) convertView.findViewById(R.id.llay_tools_dayplan_mainitem);
                mHolder.mGroupNmme = (TextView) convertView.findViewById(R.id.tv_tools_content);
                mHolder.mImgUpDown = (ImageView) convertView.findViewById(R.id.iv_toolscontent_expan);
                mHolder.mDeleteBtn = (Button) convertView.findViewById(R.id.btn_delete);
                mHolder.mMainItemLay = (LinearLayout) convertView.findViewById(R.id.llay_tools_dayplan_mainlay);
                convertView.setTag(mHolder);
            } else {
                mHolder = (GroupHolder) convertView.getTag();
            }
            mHolder.mDeleteBtn.setTag(groupPosition);
            mHolder.mDeleteBtn.setOnClickListener(ToolsPager_DayPlan_Home.this);
            mHolder.mImgUpDown.setTag(groupPosition);
            mHolder.mImgUpDown.setOnClickListener(ToolsPager_DayPlan_Home.this);
            final GroupHolder finalMHolder = mHolder;
            mHolder.mSwipeLay.setOnItemStateChanged(new SwipteLayout.OnItemStateChanged() {
                @Override
                public void onOpen(SwipteLayout layout) {
                    mSwipeLay = layout;
                }

                @Override
                public void onClose(SwipteLayout layout) {
                    if (mSwipeLay == layout) {
                        mSwipeLay = null;
                    }
                    finalMHolder.mSwipeLay.requestDisallowInterceptTouchEvent(true);
                }

                @Override
                public void onDown(SwipteLayout layout) {
                    if (mSwipeLay != null && mSwipeLay != layout) {
                        mSwipeLay.closeMenu();
                    }
                }
            });
            mHolder.mGroupNmme.setText(typeBean.getWeddingProcessClassName());
            //判断isExpanded就可以控制是按下还是关闭，同时更换图片
            if (isExpanded) {
                mHolder.mMainItemLay.setBackgroundResource(R.color.bg_colorMainGray);
                mHolder.mImgUpDown.setBackgroundResource(R.mipmap.up_gray_48);

            } else {
                mHolder.mMainItemLay.setBackgroundResource(R.color.colorWhite);
                mHolder.mImgUpDown.setBackgroundResource(R.mipmap.down_gray_48);
            }
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            List<DayplanTask.DataBean> taskData = mTypeList.get(groupPosition).getTaskData();
            if (taskData == null || taskData.size() < 1) {
                LinearLayout addLay = (LinearLayout) View.inflate(mDayplayActivity, R.layout.item_tools_dayplan_addtype, null);
                addLay.setBackgroundResource(R.color.colorMainBack);
                LinearLayout mAddTypeLay = (LinearLayout) addLay.findViewById(R.id.llay_nocontent_addtype);
                mAddTypeLay.setTag(groupPosition);
                mAddTypeLay.setOnClickListener(ToolsPager_DayPlan_Home.this);
                return addLay;
            }
            DayplanTask.DataBean dataBean = taskData.get(childPosition);
            ItemHolder holder = null;
            holder = new ItemHolder();
            convertView = View.inflate(mDayplayActivity, R.layout.item_tools_dayplan_contentdetelitem, null);
            LinearLayout mLay = (LinearLayout) convertView.findViewById(R.id.llay_tools_dayplan_detailmain);
            holder.mAddTaskLay = (LinearLayout) convertView.findViewById(R.id.lay_tools_dayplan_taskadd);
            holder.mDelTasktV = (TextView) convertView.findViewById(R.id.tv_tools_dayplan_contdetldeletetask);
            holder.mEditTypeLV = (LinearLayout) convertView.findViewById(R.id.llay_tools_dayplan_edittype1);
            holder.timetV = (TextView) convertView.findViewById(R.id.tv_tools_contentitem_time);
            holder.nemwtV = (TextView) convertView.findViewById(R.id.tv_tools_contentitem_person);
            holder.contentV = (TextView) convertView.findViewById(R.id.tv_tools_contentitem_content);
            mLay.setGravity(Gravity.CENTER_HORIZONTAL);
            holder.timetV.setText(dataBean.getWeddingProcessTime());
            holder.nemwtV.setText(dataBean.getWeddingProcessMan());
            holder.contentV.setText(dataBean.getWeddingProcessThing());
            holder.mAddTaskLay.setTag(groupPosition);
            holder.mAddTaskLay.setOnClickListener(ToolsPager_DayPlan_Home.this);
            holder.mDelTasktV.setTag(childPosition);
            holder.mDelTasktV.setTag(R.id.tag_first, groupPosition);
            holder.mDelTasktV.setOnClickListener(ToolsPager_DayPlan_Home.this);
            holder.mEditTypeLV.setTag(R.id.tag_first, groupPosition);
            holder.mEditTypeLV.setTag(R.id.tag_second, childPosition);
            holder.mEditTypeLV.setOnClickListener(ToolsPager_DayPlan_Home.this);
            if (isLastChild) {
                holder.mAddTaskLay.setVisibility(View.VISIBLE);
                mCurrentGroupPosition = groupPosition;
                ImageView mAddType = (ImageView) convertView.findViewById(R.id.iv_tools_dayplan_contdetladdtask);
                mAddType.setTag(groupPosition);
                mAddType.setOnClickListener(ToolsPager_DayPlan_Home.this);

            }
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        @Override
        public void onGroupCollapsed(int groupPosition) {
            mContentview.postInvalidate();
            super.onGroupCollapsed(groupPosition);
        }

        class GroupHolder {
            SwipteLayout mSwipeLay;
            TextView mGroupNmme;
            ImageView mImgUpDown;
            LinearLayout mMainItemLay;
            Button mDeleteBtn;

        }
        class ItemHolder {
            LinearLayout mAddTaskLay;
            TextView nemwtV;
            TextView timetV;
            TextView contentV;
            TextView mDelTasktV;
            LinearLayout mEditTypeLV;
        }
    }
    public void showDialog() {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mDayplayActivity).inflate(
                R.layout.confirm_dialog_add, null);
        mTypeTitle = (EditText) contentView.findViewById(R.id.title);
        TextView cancelTv = (TextView) contentView.findViewById(R.id.cancel);
        TextView confirmTv = (TextView) contentView.findViewById(R.id.confirm);
        cancelTv.setOnClickListener(ToolsPager_DayPlan_Home.this);
        confirmTv.setOnClickListener(ToolsPager_DayPlan_Home.this);
        popupWindow1 = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        //设置位置
        popupWindow1.showAtLocation(mHeadAddtype, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        //点击空白处时，隐藏掉pop窗口
        popupWindow1.setTouchable(false);
        popupWindow1.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow1.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
    }

    /**
     * 添加新流程类型
     */
    private void addTypetoServer(String data) {
        showCommitPopupWindow(mHeadAddtype);
        String wedType = data;
        String url = UrlDealUtil.getRealUrl(RequestCode.ADDTYPEWEDDINGPROCESS);
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("WeddingProcessClassName", wedType);
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, CommonResultBean.class, RequestCode.ADDTYPEWEDDINGPROCESS, paramsMap);
        HttpHandleUtil.executeCommonPost(mDayplayActivity, httpRequestBean);
    }

    private void deleteTypetoServer(int wedClassSysID) {
        showCommitPopupWindow(mHeadAddtype);
        String wedTypeId = wedClassSysID + "";
        String url = UrlDealUtil.getRealUrl(RequestCode.DELECTWEDDINGPROCESSCLASS);
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("WeddingProcessClassID", wedTypeId);
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, CommonResultBean.class, RequestCode.ADDTYPEWEDDINGPROCESS, paramsMap);
        HttpHandleUtil.executeCommonPost(mDayplayActivity, httpRequestBean);
        isDeleteType = true;
    }

    private void deleteTasktoServer() {
        showCommitPopupWindow(mHeadAddtype);
        //从服务器删除
        String url = UrlDealUtil.getRealUrl(RequestCode.DELECTWEDDINGPROCESS);
        HashMap<String, String> paramsMap = new HashMap<>();
        WedPlanTypeBean.DataBean dataBean2 = mTypeList.get(groupPosition2);
        int weddingProcessID = dataBean2.getTaskData().get(childPosition2).getWeddingProcessID();
        paramsMap.put("WeddingProcessClassID", String.valueOf(dataBean2.getWeddingProcessClassID()));
        paramsMap.put("WeddingProcessID", "" + weddingProcessID);
        HttpRequestBean delTaskHttp = new HttpRequestBean(RequestCode.POSTEQUEST, url, ToolsPager_DayPlan_Home.this,
                CommonResultBean.class, RequestCode.DELECTWEDDINGPROCESS, paramsMap);
        HttpHandleUtil.executeCommonPost(mDayplayActivity, delTaskHttp);
        isDeleteTAsk = true;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llay_toolsheader_back:
                mDayplayActivity.finish();
                break;
            case R.id.tv_addtype://添加新类型
                showDialog();
                break;
            case R.id.llay_nocontent_addtype://添加新类型
                mCurrentGroupPosition = (int) view.getTag();
                mDayplayActivity.setmCurrentGroupPosition(mCurrentGroupPosition);
                isEditType = false;
                mDayplayActivity.setEdit(false);
                callBack.jump("添加任务流程", this);
                break;
            case R.id.lay_tools_dayplan_taskadd://添加当天任务流程
                mCurrentGroupPosition = (int) view.getTag();
                mDayplayActivity.setmCurrentGroupPosition(mCurrentGroupPosition);
                isEditType = false;
                mDayplayActivity.setEdit(false);
                callBack.jump("添加任务流程", this);
                break;
            case R.id.llay_tools_dayplan_edittype1://修改任务
                mCurrentGroupPosition = (int) view.getTag(R.id.tag_first);
                mCurrentChildPosition = (int) view.getTag(R.id.tag_second);
                isEditType = true;
                mDayplayActivity.setmCurrentGroupPosition(mCurrentGroupPosition);
                mDayplayActivity.setmCurrentChildPosition(mCurrentChildPosition);
                mDayplayActivity.setEdit(true);
                callBack.jump("添加任务流程", this);
                break;
            case R.id.tv_tools_dayplan_contdetldeletetask://删除当天任务流程
                childPosition2 = (int) view.getTag();
                groupPosition2 = (int) view.getTag(R.id.tag_first);
                showDelTaskDialog(mDayplayActivity, "您确定删除此任务？", "确定", "取消");
                break;
            case R.id.iv_tools_dayplan_modeladd:
                CUtils.showToast("请登录后再操作");
                break;
            case R.id.iv_tools_dayplan_swipe:
                if (isDetailShow) {
                    mContentItem.setBackgroundResource(R.color.colorWhite);
                    modeldeail.setVisibility(View.GONE);
                    mSwipeView.setBackgroundResource(R.mipmap.down_gray_48);
                    isDetailShow = false;
                } else {
                    mContentItem.setBackgroundResource(R.color.bg_colorMainGray);
                    modeldeail.setVisibility(View.VISIBLE);
                    mSwipeView.setBackgroundResource(R.mipmap.up_gray_48);
                    isDetailShow = true;
                }
                break;
            case R.id.tv_tools_dayplan_addtype:
                showDialog();
                break;
            case R.id.tv_tools_dayplan_addtype1:
                showShare();
                break;
            case R.id.btn_delete://删除类型
                groupPosition = (int) view.getTag();
                showDialog(mDayplayActivity, "您确定删除此流程类型？", "确定", "取消");
                break;
            case R.id.iv_toolscontent_expan:
                int groupposition = (int) view.getTag();
                if (mContentList.isGroupExpanded(groupposition)) {
                    mContentList.collapseGroup(groupposition);
                } else {
                    mContentList.expandGroup(groupposition);
                }
                break;
            case R.id.cancel:
                if (popupWindow1 != null) {
                    popupWindow1.dismiss();
                }
                break;
            case R.id.btn_tools_dayplan_restore://恢复默认流程
                isRecoverType = true;
                mProgressbar.setVisibility(View.VISIBLE);
                String reurl = UrlDealUtil.getRealUrl(RequestCode.RECOVERYWEDDINGPROCESS);
                HttpRequestBean reHttp = new HttpRequestBean(RequestCode.POSTEQUEST, reurl, this,
                        CommonResultBean.class, RequestCode.RECOVERYWEDDINGPROCESS);
                HttpHandleUtil.executeCommonPost(mDayplayActivity, reHttp);
                break;
            case R.id.confirm://添加类型
                isaddType = true;
                String typeName = mTypeTitle.getText().toString().trim();
                if (TextUtils.isEmpty(typeName)) {
                    CUtils.showToast("类型名称不能为空！");
                    return;
                }
                mDayPlantype = typeName;
                //将信息发送到服务器
                addTypetoServer(typeName);
                if (popupWindow1 != null) {
                    popupWindow1.dismiss();
                }
                break;
            case R.id.llay_netfailer:
                getDataFromServer();
                break;

        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        mNetWorkFail.setVisibility(View.GONE);
        Object objdata = sucessbean.getData();
        refreshView(HAVEDATA);
        if (objdata instanceof CommonResultBean) {
            CommonResultBean commonresult = (CommonResultBean) objdata;
            switch (commonresult.getResCode()) {
                case "0000":
                    if (mCommitpop != null) {
                        mCommitpop.dismiss();
                    }
                    if (isRecoverType) {
                        getDataFromServer();
                    }
                    if (isDeleteTAsk) {
                        mTypeList.get(groupPosition2).getTaskData().remove(childPosition2);
                        collectGroup();
                        if (mExpandAdapter != null) {
                            mExpandAdapter.notifyDataSetChanged();
                            mContentList.collapseGroup(mTypeList.size() - 1);
                            mContentList.expandGroup(mTypeList.size() - 1);
                            mContentList.collapseGroup(mTypeList.size() - 1);
                            if (mSwipeLay != null) {
                                mSwipeLay.closeMenu();
                            }
                        }
                        if (mSwipeLay != null) {
                            mSwipeLay.closeMenu();
                        }
                        isDeleteTAsk = false;
                        return;
                    } else if (isDeleteType) {
                        mTypeList.remove(groupPosition);
                        if (mTypeList.size() == 0) {
                            refreshView(NODATA);
                            return;
                        }
                        if (mExpandAdapter != null) {
                            mExpandAdapter.notifyDataSetChanged();
                            mContentList.collapseGroup(mTypeList.size() - 1);
                            mContentList.expandGroup(mTypeList.size() - 1);
                            mContentList.collapseGroup(mTypeList.size() - 1);
                            if (mSwipeLay != null) {
                                mSwipeLay.closeMenu();

                            }
                        }
                        if (mSwipeLay != null) {
                            mSwipeLay.closeMenu();
                        }
                        isDeleteType = false;
                        return;
                    } else if (isaddType) {
                        isaddType = false;
                    }

                    if (mSwipeLay != null) {
                        mSwipeLay.closeMenu();
                    }
                    getDataFromServer();
                    break;
                case "0001":
                case "0002":
                    if (mCommitpop != null) {
                        mCommitpop.dismiss();
                    }
                    CUtils.showToast("数据请求失败！");
                    break;
                case "0003":
                    if (mCommitpop != null) {
                        mCommitpop.dismiss();
                    }
                    break;
            }


        } else if (objdata instanceof WedPlanTypeBean) {
            WedPlanTypeBean mDayPlanType = (WedPlanTypeBean) objdata;
            String resCode = mDayPlanType.getResCode();
            String msg = mDayPlanType.getMsg();
            switch (resCode) {
                case "0000":
                    mTypeList = mDayPlanType.getData();
                    mDayplayActivity.setmTypeList(mTypeList);
                    RequestParams requestParams = null;
                    if (mTypeList != null && mTypeList.size() > 0) {
                        for (int i = 0; i < mTypeList.size(); i++) {
                            final WedPlanTypeBean.DataBean databean = mTypeList.get(i);
                            String url = UrlDealUtil.getRealUrl(RequestCode.WEDDINGPROCESS);
                            requestParams = new RequestParams(url);
                            requestParams.addBodyParameter("WeddingProcessClassID", String.valueOf(databean.getWeddingProcessClassID()));
                            x.http().post(requestParams, new Callback.CommonCallback<String>() {
                                @Override
                                public void onSuccess(String result) {
                                    if (!TextUtils.isEmpty(result)) {
                                        try {
                                            Gson mGson = new Gson();
                                            String newjsondata = StrUtil.jsonStr(result);
                                            DayplanTask mTask = null;
                                            if (newjsondata.contains("暂无数据")) {
                                                mTask = new DayplanTask();
                                            } else {
                                                mTask = mGson.fromJson(newjsondata, DayplanTask.class);
                                            }
                                            databean.setTaskData(mTask.getData());
                                            childNetRequest++;
                                            if (childNetRequest == mTypeList.size()) {
                                                mHandler.sendEmptyMessage(CHILDNETREQUESTSUCESS);
                                            }
                                        } catch (Exception e) {
                                            mHandler.sendEmptyMessage(CHILDNETREQUESTFAIL);
                                        }
                                    }
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                }

                                @Override
                                public void onCancelled(CancelledException cex) {
                                }

                                @Override
                                public void onFinished() {
                                }
                            });

                        }
                    }
                    if (mExpandAdapter != null) {
                        mExpandAdapter.notifyDataSetChanged();
                    }
                case "0001":
                case "0002":
                case "0003":
                    if (mCommitpop != null) {
                        mCommitpop.dismiss();
                    }
                    refreshView(NODATA);
                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        if (mCommitpop != null) {
            mCommitpop.dismiss();
        }
        switch (errorBean.getErrorCode()) {
            case ErrorBean.NONET:
            case ErrorBean.TIMEOUT:
                refreshView(NONET);
                CUtils.showToast("网络连接失败！");
                break;
            case ErrorBean.DATAERROR:
                CUtils.showDataErrToast(mDayplayActivity);
                break;
            default:
                CUtils.showDataErrToast(mDayplayActivity);
                break;
        }

    }


    public void showCommitPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mDayplayActivity).inflate(
                R.layout.pop_tools_wedregister_commit, null);
        mCommitpop = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        //点击空白处时，隐藏掉pop窗口
        mCommitpop.setTouchable(true);
        mCommitpop.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        //设置位置
        mCommitpop.showAtLocation(mContentview.findViewById(R.id.llay_toolsheader_back), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);//设置在屏幕中的显示位置
        mCommitpop.setBackgroundDrawable(new BitmapDrawable());
        // 设置好参数之后再show
        mCommitpop.showAsDropDown(view);
    }

    /**
     * 设置添加屏幕的背景透明度 * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = mDayplayActivity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
    }

    private void setParams(RequestParams requestParams, HashMap<String, String> paramsMap) {
        Set<Map.Entry<String, String>> entries = paramsMap.entrySet();
        for (Map.Entry<String, String> entryset : entries) {
            requestParams.addBodyParameter(entryset.getKey(), entryset.getValue());
        }
    }

    public void showDialog(Context context, String title, String confirm, String cancel) {
        final ConfirmDialog confirmDialog = new ConfirmDialog(context, title, confirm, cancel, R.layout.confirm_dialog);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                int weddingProcessClassSysID = mTypeList.get(groupPosition).getWeddingProcessClassID();
                deleteTypetoServer(weddingProcessClassSysID);
                confirmDialog.dismiss();
            }

            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }

    public void showDelTaskDialog(Context context, String title, String confirm, String cancel) {
        final ConfirmDialog confirmDialog = new ConfirmDialog(context, title, confirm, cancel, R.layout.confirm_dialog);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                isDeleteTAsk = true;
                deleteTasktoServer();
                confirmDialog.dismiss();
            }

            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }

    @Override
    public void notifyData(String pageName) {
        getDataFromServer();
    }
    public void refreshView(int state) {
        switch (state) {
            case HAVEDATA:
                mProgressbar.setVisibility(View.GONE);
                if (mdataContentLay.isShown()) {
                    return;
                } else {
                    mdataContentLay.setVisibility(View.VISIBLE);
                }
                mNoDataLay.setVisibility(View.GONE);
                break;
            case DATAERROR:
            case NODATA:
                mProgressbar.setVisibility(View.GONE);
                mdataContentLay.setVisibility(View.GONE);
                mNoDataLay.setVisibility(View.VISIBLE);
                break;
            case NONET:
                mNetWorkFail.setVisibility(View.VISIBLE);
                mProgressbar.setVisibility(View.GONE);
                mdataContentLay.setVisibility(View.GONE);
                mNoDataLay.setVisibility(View.GONE);
                break;
        }
    }
    public void getDataFromServer() {
        String realUrl = UrlDealUtil.getRealUrl(RequestCode.WEDDINGPROCESSTYPE);
        HttpRequestBean httpBean = new HttpRequestBean(RequestCode.POSTEQUEST, realUrl, this, WedPlanTypeBean.class, RequestCode.WEDDINGPROCESSTYPE);
        HttpHandleUtil.executeCommonPost(mDayplayActivity, httpBean);

    }
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CHILDNETREQUESTSUCESS:
                    //显示界面
                    refreshView(HAVEDATA);
                    if (mTypeList != null && mTypeList.size() > 0) {
                        childNetRequest = 0;
                        mExpandAdapter = new MyExpandListAdapter();
                        mContentList.setAdapter(mExpandAdapter);
                        mContentList.setGroupIndicator(null);
                        mContentList.collapseGroup(mTypeList.size() - 1);
                        mContentList.expandGroup(mTypeList.size() - 1);
                        mContentList.collapseGroup(mTypeList.size() - 1);
                        setListViewHeightBasedOnChildren(mContentList);
                        mContentList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
                            @Override
                            public void onGroupExpand(int groupPosition) {
                                /**
                                 * 计算group下的子项的高度
                                 */
                                setExpandedListViewHeightBasedOnChildren(mContentList, groupPosition);
                                // 更新group每一项的高度

                            }
                        });
                        mContentList.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
                            @Override
                            public void onGroupCollapse(int groupPosition) {
                                setCollapseListViewHeightBasedOnChildren(mContentList,
                                        groupPosition);
                                setListViewHeightBasedOnChildren(mContentList);

                            }
                        });
                    }
                    if (popCount == 0) {
                        if (mBackView.isShown()) {
                            showPopupWindow(mBackView);
                        }
                        popCount++;
                    }
                    break;
                case CHILDNETREQUESTFAIL:
                    refreshView(DATAERROR);
                    break;
                case NETWORKTIME:
                    if (mProgressbar.isShown()) {
                        refreshView(NONET);
                    }
                    break;
            }
        }
    };
    public void collectGroup() {
        if (mExpandAdapter != null) {
            for (int i = 0; i < mTypeList.size(); i++) {
                if (i == mCurrentGroupPosition) {
                    continue;
                }
                mContentList.collapseGroup(i);
            }
        }
    }

    private void showPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mDayplayActivity).inflate(
                R.layout.pop_tools_dayplan_msg, null);
        msgPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        msgPopupWindow.setFocusable(true);

        // 设置按钮的点击事件
        ImageView button = (ImageView) contentView.findViewById(R.id.iv_delete);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgPopupWindow.dismiss();
            }
        });
        //点击空白处时，隐藏掉pop窗口
        msgPopupWindow.setTouchable(true);
        //在PopupWindow里面就加上下面代码，让键盘弹出时，不会挡住pop窗口。
        msgPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置位置

        msgPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                msgPopupWindow.dismiss();
                return true;
            }
        });
        msgPopupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.whitetranslucenthalf2)));
        msgPopupWindow.showAtLocation(mContentview.findViewById(R.id.llay_toolsheader_back), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public static void setListViewHeightBasedOnChildren(ExpandableListView listView) {
        // 获取ListView对应的Adapter
        ExpandableListAdapter listAdapter = listView.getExpandableListAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getGroupCount(); i++) { // listAdapter.getCount()返回数据项的数目
            View listgroupItem = listAdapter.getGroupView(i, true, null, listView);
            listgroupItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listgroupItem.getMeasuredHeight(); // 统计所有group项的总高度
            boolean groupExpanded = listView.isGroupExpanded(i);

            if (groupExpanded) {

                for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
                    View listchildItem = listAdapter.getChildView(i, j, false, null, listView);
                    listchildItem.measure(0, 0); // 计算子项View 的宽高
                    totalHeight += listchildItem.getMeasuredHeight(); // 统计所有子项的总高度
                }
            }
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
        listView.setLayoutParams(params);
    }


    private void setListViewHeight(ExpandableListView listView, int group) {
        ExpandableListAdapter listAdapter = listView.getExpandableListAdapter();
        //总高度
        int totalHeight = 0;
        //期望的宽度
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
        for (int i = 0; i < listAdapter.getGroupCount(); i++) {
            //得到一级条目
            View groupItem = listAdapter.getGroupView(i, false, null, listView);
            groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            //累加一级条目高度
            totalHeight += groupItem.getHeight();
            if (((listView.isGroupExpanded(group)) && (i != group)) || ((!listView.isGroupExpanded(group)) && (i == group))) {
                for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
                    //得到二级条目
                    View listItem = listAdapter.getChildView(i, j, false, null, listView);
                    //listItem根据给的参数测量一下尺寸，方法调用完后listItem大小就确定了
                    listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                    //累加二级条目高度
                    totalHeight += listItem.getHeight();
                }
            }
        }
        //获得listView的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        int height = totalHeight + (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
        //如果高度小于10，则设置为200，没有太大关系
        if (height < 10) {
            height = 200;
        }
        //把高度赋值给布局参数
        params.height = height;
        listView.setLayoutParams(params);
        listView.requestLayout();
    }


    /**
     * 动态改变listView的高度
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        ((ViewGroup.MarginLayoutParams) params).setMargins(0, 0, 0, 0);
        listView.setLayoutParams(params);

    }

    /**
     * 可扩展listview展开时调用
     *
     * @param listView
     * @param groupPosition
     */
    public static void setExpandedListViewHeightBasedOnChildren(
            ExpandableListView listView, int groupPosition) {
        ExpandableListAdapter listAdapter = listView.getExpandableListAdapter();
        if (listAdapter == null) {
            return;
        }

        int appendHeight = 0;
        for (int i = 0; i < listAdapter.getChildrenCount(groupPosition); i++) {
            View listItem = listAdapter.getChildView(groupPosition, i, false, null, listView);
            listItem.measure(0, 0);

            appendHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height += appendHeight;
        listView.setLayoutParams(params);
    }

    /**
     * 可扩展listview收起时调用
     *
     * @param listView
     * @param groupPosition
     */
    public static void setCollapseListViewHeightBasedOnChildren(
            ExpandableListView listView, int groupPosition) {
        ExpandableListAdapter listAdapter = listView.getExpandableListAdapter();
        if (listAdapter == null) {
            return;
        }
        View listItem = listAdapter.getChildView(groupPosition, 0, true, null,
                listView);
        listItem.measure(0, 0);
        int appendHeight = 0;
        for (int i = 0; i < listAdapter.getChildrenCount(groupPosition); i++) {
            appendHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height -= appendHeight;
        listView.setLayoutParams(params);
    }

    /**
     * 一键分享
     */
    private void showShare() {
        String title = "结婚通";
        String description = "幸福从哪里开始，幸福从这里开始！";
        String url = "http://j.66wedding.com/downLoad.html";
        copyToSD(mActivity);
//        getShareUtils();
        ShareSDK.initSDK(mActivity);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(title);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(description);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        String path = android.os.Environment.getExternalStorageDirectory().getPath() + "/" + "pic_share_0214.jpg";
        oks.setImagePath(path);//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(description);
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(url);
        // 启动分享GUI
        oks.show(mActivity);
    }


    private static File file;

    /**
     * 把raw的图片存到SD卡上
     */
    public static void copyToSD(Context context) {
        InputStream is = null;
        FileOutputStream fos = null;

        try {
            String path = android.os.Environment.getExternalStorageDirectory()
                    .getPath();
            String dbPathAndName = path + "/" + "pic_share_0214.jpg";

            file = new File(path);

            if (file.exists() == false) {

                file.mkdir();
            }
            File dbFile = new File(dbPathAndName);
            if (!dbFile.exists()) {
                is = context.getResources().openRawResource(
                        R.raw.pic_share);
                fos = new FileOutputStream(dbFile);

                byte[] buffer = new byte[8 * 1024];// 8K
                while (is.read(buffer) > 0)// >
                {
                    fos.write(buffer);
                }
            }
        } catch (Exception e) {

        } finally {
            try {
                if (is != null) {
                    is.close();
                }

                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
